# backend/app/db/db_handler.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from .db_models import Base
import logging
import os

BACKEND_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


class DatabaseHandler:
    def __init__(self):
        from app.config import settings
        # 创建数据库引擎
        self.engine = create_engine(settings.SQLALCHEMY_DATABASE_URL)
        # 创建会话工厂
        self.Session = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)

        # 创建日志记录器
        self.logger = logging.getLogger(__name__)

    def get_session(self):
        """获取数据库会话"""
        return self.Session()

    def migrate_database(self):
        """执行数据库迁移"""
        try:
            from alembic.config import Config
            from alembic import command

            # 加载 Alembic 配置
            alembic_cfg = Config("alembic.ini")

            # 执行迁移
            command.upgrade(alembic_cfg, "head")

            self.logger.info("数据库迁移成功")
        except Exception as e:
            self.logger.error(f"数据库迁移失败: {str(e)}")
            raise

# 创建单例实例
database_handler = DatabaseHandler()

# 定义依赖函数
def get_database_handler():
    return database_handler

def get_db():
    return database_handler.get_session()
